Hi all,
I’ve been trawling the forums trying to find a solution for this.
We have an ACF field group called Additional Course Data group_5edb89be3792c which contains several fields including course_code.
This is assigned to Learndash Courses post type.
Each course requires a course_code which must be unique.
I’m trying to create a function that will reside in my child theme functions.php – that checks to see if the code is unique whenever a user clones or creates a new course and then checks the course_code is unique when they try to publish, and if it’s not unique, then display a warning “Course Code must be unique” so that the course_code is edited before publishing.
I’m not the greatest PHP developer in the world, so I’ve tried using codewp.ai to give me the basics, but I just can’t get it to work.
Any pointers would be greatly appreciated.I’ve been trawling the forums trying to find a solution for this.
This is where I’m at, but can’t get this to work
// Check that course code is unique
function cwpai_check_course_code_unique() {
global $post;
if (get_post_type($post) == 'sfwd-courses') {
$course_code = get_field('course_code', $post->ID);
$args = array(
'post_type' => 'sfwd-courses',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'course_code',
'value' => $course_code,
'compare' => '='
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
$query->the_post();
if ($post->ID != $post->ID) {
$url = admin_url('post.php?post=' . $post->ID . '&action=edit');
$message = sprintf(__('The course code %s is already in use by %s. Please choose a unique course code.', 'cwpai'), $course_code, '<a href="' . $url . '">' . get_the_title() . '</a>');
?>
<div class="error">
<p><?php echo $message; ?></p>
</div>
<?php
}
}
}
}
add_action('admin_notices', 'cwpai_check_course_code_unique');
Hi,
I try to use front-end forms.
I registered form and use it in template.
add_action('init', 'init_forms');
function init_forms()
form_register();
}
function form_register()
{
if (is_admin() || is_admin_login_page()) {
return;
}
$pageAccount = get_page_with_shortcode('ACCOUNT_SHORTCODE');
$permalinkAccount = get_permalink($pageAccount->ID);
if (empty($permalinkAccount)) {
$permalinkAccount = '';
}
if (check_current_url_equals_shortcode('ACCOUNT_SHORTCODE_REGISTER')) {
acf_register_form(array(
'id' => 'new_member',
'post_id' => 'new_post',
'new_post' => array(
'post_type' => 'member',
'post_status' => 'publish',
),
'honeypot' => true,
// 'field_groups' => array('group_64ae62c8e220b'),
'fields' => [
LASTNAME_FIELD,
FIRSTNAME_FIELD,
EMAIL_FIELD,
EMAIL_FIELD . 'repeat',
PHONE_FIELD,
PASSWORD_FIELD,
PASSWORD_FIELD . 'repeat',
GENDER_FIELD,
],
'form' => true,
'updated_message' => __('Informations saved !', 'onlyweb'),
'submit_value' => __('Save profile', 'onlyweb'),
'html_submit_button' => '<input type="submit" class="btn acf-button button button-primary button-large" value="%s" />',
'return' => add_query_arg(array('updated' => 'true'), $permalinkAccount),
));
}
}
I added validation for field like exmple below :
add_filter('acf/validate_value/key=' . EMAIL_FIELD . 'repeat', 'my_acf_validate_check_login_are_same', 10, 4);
function my_acf_validate_check_login_are_same($valid, $value, $field, $input)
{
// bail early if value is already invalid
if (!$valid) {
return $valid;
}
if (!is_admin()) {
// Remove all errors if user is an administrator.
if (current_user_can('manage_options')) {
acf_reset_validation_errors();
}
$login = (!empty($_POST['acf'][EMAIL_FIELD])) ? $_POST['acf'][EMAIL_FIELD] : false;
$loginRepeat = (!empty($_POST['acf'][EMAIL_FIELD . 'repeat'])) ? $_POST['acf'][EMAIL_FIELD . 'repeat'] : false;
if ($login != $loginRepeat) {
$valid = __('Email are not the same !', 'onlyweb');
$valid = 'error 2';
// return $valid;
}
}
return $valid;
}
The problem appears when I submit the form, error are shown on an other error page.
Any solution ?
I’m trying to use ACF Pro to create a form that people can submit, which should then create a draft post.
The ACF Field Group is there and renders on the page.
Upon submitting the form, it does display a positive confirmation message but no post has been created.
What am I doing wrong?
I have created a custom theme with the following file:
<?php
acf_form_head();
get_header();
?>
<div id="content">
<div class="wrap">
<form id='post' class='acf-form' action='' method='post'>
<?php
acf_form([
'field_groups' => ['group_5***d'],
'post_id' => 'new_post',
'post_title' => false,
'post_content' => false,
'post_category' => 'academy',
'form' => false,
'submit_value' => __("Submit post", 'acf'),
'updated_message' => __("Thank you!", 'acf'),
'html_updated_message' => '<div id="message" class="updated"><p>%s</p></div>'
]);
if(current_user_can('activate_plugins')) {
acf_form([
'field_groups' => ['group_5***b'],
'post_id' => 'new_post',
'post_category' => 'academy',
'form' => false
]);
}
?>
<div class="acf-form-submit">
<input type="submit" class="acf-button" value="Submit post">
<span class="acf-spinner"></span>
</div>
</form>
</div>
</div>
<?php get_footer();
And I have the following code snippet:
function savePostsAsAcademyDraft($post_id) {
$term = get_term_by('slug', 'academy', 'category');
wp_update_post([
'ID' => $post_id,
'post_status' => 'draft',
'post_category' => [/*$term->id*/3]
]);
return $post_id;
}
add_filter('acf/pre_save_post' , 'savePostsAsAcademyDraft', 10, 1);
I have a repeater that has a read-only field that has a shortcode with an unique id. I need this ID, so I can have shortcodes that can output the other values in the repeater row.
This is the (summarized) way I add fields:
acf_add_local_field_group(
'key' => 'pricing_group',
'title' => 'Pricing',
'fields' => [
'key' => 'pricing_user_monthly_fees',
'label' => 'User Monthly Fees',
'name' => 'user_monthly_fees',
'type' => 'repeater',
'instructions' => 'Please create different fee ranges depending on the amount of users the customer wants to sign-up for.',
'layout' => 'table',
'button_label' => 'Add Range',
'sub_fields' => [
[
'key' => 'pricing_user_monthly_fees_minimum',
'label' => 'Minimum',
'name' => 'minimum',
'type' => 'number',
'instructions' => 'Please enter a minimum value for this range.',
'wrapper' => [ 'width' => '20' ],
'min' => 0,
'parent_repeater' => 'pricing_user_monthly_fees',
],
[
'key' => 'pricing_user_monthly_fees_maximum',
'label' => 'Maximum',
'name' => 'maximum',
'type' => 'number',
'instructions' => 'Please enter a maximum value for this range.',
'wrapper' => [ 'width' => '20' ],
'min' => 0,
'parent_repeater' => 'pricing_user_monthly_fees',
],
[
'key' => 'pricing_user_monthly_fees_fee',
'label' => 'Fee',
'name' => 'fee',
'type' => 'number',
'instructions' => 'Please enter a fee for this range.',
'wrapper' => [ 'width' => '20' ],
'parent_repeater' => 'pricing_user_monthly_fees',
],
[
'key' => 'pricing_user_shortcode',
'label' => 'Shortcode',
'name' => 'shortcode',
'type' => 'text',
'readonly' => 1,
'instructions' => 'When you save this range, a shortcode is generated as a read-only field. You can use this shortcode to display the range\'s fee.',
'wrapper' => [ 'width' => '40' ],
'parent_repeater' => 'pricing_user_monthly_fees',
],
],
],
'location' => [
[
[
'param' => 'options_page',
'operator' => '==',
'value' => 'acf-options-pricing',
],
],
],
);
This is the function that generates a shortcode with an unique id:
public function store_unique_shortcode(string $post_id)
{
$screen = get_current_screen();
if ($post_id !== 'options'
&& !isset($screen->id)
&& !strpos($screen->id, 'acf-options-pricing')) { return; }
$field = get_field('pricing_user_monthly_fees', $post_id);
if (!$field) { return; }
$user_monthly_fees = array_map(function($user_monthly_fee) {
return array_merge($user_monthly_fee, [
'shortcode' => $user_monthly_fee['shortcode'] ?:
sprintf('[pricing_user_monthly_fee id="%s"]', uniqid()),
]);
}, $field);
update_field('pricing_user_monthly_fees', $user_monthly_fees, $post_id);
}
The problem is that when I use get_field() it shows an empty shortcode value while I expect it to contain the shortcode string with a unique id.
If I dump $field I get the following:
array(1) {
[0]=>
array(4) {
["minimum"]=>
string(1) "0"
["maximum"]=>
string(1) "3"
["fee"]=>
string(4) "18.5"
["shortcode"]=>
string(0) ""
}
}
If I dump $user_monthly_fees I get the array with the shortcode and the generated unique id.
array(1) {
[0]=>
array(4) {
["minimum"]=>
string(1) "0"
["maximum"]=>
string(1) "3"
["fee"]=>
string(4) "18.5"
["shortcode"]=>
string(50) "[pricing_user_monthly_fee id="646c94d8b29f2"]"
}
}
If I dump right after update_field() I get an array with an empty shortcode value.
array(1) {
[0]=>
array(4) {
["minimum"]=>
string(1) "0"
["maximum"]=>
string(1) "3"
["fee"]=>
string(4) "18.5"
["shortcode"]=>
string(0) ""
}
}
Why doesn’t get_field() return the shortcode with the generated unique id?
Hello.
I need some help improving the output of the gallery field so that it is responsive and adding a lightbox effect.
Below is my code:
<?php
// Load value (array of ids).
$image_ids = get_field('our_past_work');
if( $image_ids ) {
// Generate string of ids ("123,456,789").
$images_string = implode( ',', $image_ids );
// Generate and do shortcode.
// Note: The following string is split to simply prevent our own website from rendering the gallery shortcode.
$shortcode = sprintf( '[' . 'gallery ids="%s"]', esc_attr($images_string) );
echo do_shortcode( $shortcode );
}
?>
If there is another free plugin i can use apart from Simple Lightbox, i am happy to try it. Thank you in advance.
Hi, I’m trying to search a post which have a meta value that contains one of these values: 1408 or 1407. Within the postmeta table I have this:
a:3:{i:0;s:4:”1406″;i:1;s:4:”1407″;i:2;s:4:”1408″;}
So I’ve created a function which contains the following:
function add_related_posts_to_search( $query ) {
if( $query->is_search ) {
$search_term = $query->query_vars['s'];
$query->query_vars['s'] = '';
$post_ids = search_medici_in_servizio_title( $search_term );
if( ! empty( $post_ids ) ) {
$meta_query = array();
foreach($post_ids as $pi) {
$meta_query[] = array(
'key' => 'medici',
'value' => sprintf("'%s'", $pi),
'compare' => 'LIKE',
);
}
$query->set('meta_query', $meta_query);
}
}
}
add_action( 'pre_get_posts', 'add_related_posts_to_search' );
essentially I’m getting all the id of the posts that have the searched term (in this case is returned an array with 1407 and 1408), and then I’ve mounted a meta_query that should return all the posts that contains one of the values specified.
For some reason I doesn’t get any result, any idea?
Working in the functions.php file to send an email when a custom post type is published.
If i hard code in the value for the post id it works fine and i can get the value of the post id set to $ID but when I try and insert the variable $ID into the get_field function it returns nothing.
function notify_client_on_publish( $new_status, $old_status, $post ) {
if ( 'publish' !== $new_status || $new_status === $old_status || 'clientnotes' !== get_post_type( $post ) ) {
return;
}
if ( ! $user = get_userdata( $post->post_author ) ) {
return;
}
$ID = $post->ID;
$post_meta_user = get_post_meta($ID, 'client', true);
$client = get_field('client', $ID);
$body = sprintf( "<%s> latest_cpt <%s>", $client, $ID );
wp_mail( $user->user_email, 'New Message from VSB Performance!', $body );
}
add_action( 'transition_post_status', 'notify_client_on_publish', 20, 3 );
here’s the code with acf fields functionality, I’ve been doing this for straight 8 hours but I can’t figured it out.
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Upload presale permit certificate:<span title="required">*</span></label>
<?php
acf_form_head();
$settings = array(
/* (string) Unique identifier for the form. Defaults to 'acf-form' */
'id' => 'acf-form',
/* (int|string) The post ID to load data from and save data to. Defaults to the current post ID.
Can also be set to 'new_post' to create a new post on submit */
'post_id' => false,
/* (array) An array of post data used to create a post. See wp_insert_post for available parameters.
The above 'post_id' setting must contain a value of 'new_post' */
'new_post' => false,
/* (array) An array of field group IDs/keys to override the fields displayed in this form */
'field_groups' => false,
/* (array) An array of field IDs/keys to override the fields displayed in this form */
'fields' => false,
/* (boolean) Whether or not to show the post title text field. Defaults to false */
'post_title' => false,
/* (boolean) Whether or not to show the post content editor field. Defaults to false */
'post_content' => false,
/* (boolean) Whether or not to create a form element. Useful when a adding to an existing form. Defaults to true */
'form' => false,
/* (array) An array or HTML attributes for the form element */
'form_attributes' => array(),
/* (string) The URL to be redirected to after the form is submit. Defaults to the current URL with a GET parameter '?updated=true'.
A special placeholder '%post_url%' will be converted to post's permalink (handy if creating a new post)
A special placeholder '%post_id%' will be converted to post's ID (handy if creating a new post) */
'return' => '',
/* (string) Extra HTML to add before the fields */
'html_before_fields' => '',
/* (string) Extra HTML to add after the fields */
'html_after_fields' => '',
/* (string) The text displayed on the submit button */
'submit_value' => false,
/* (string) A message displayed above the form after being redirected. Can also be set to false for no message */
'updated_message' => __("Post updated", 'acf'),
/* (string) Determines where field labels are places in relation to fields. Defaults to 'top'.
Choices of 'top' (Above fields) or 'left' (Beside fields) */
'label_placement' => false,
/* (string) Determines where field instructions are places in relation to fields. Defaults to 'label'.
Choices of 'label' (Below labels) or 'field' (Below fields) */
'instruction_placement' => false,
/* (string) Determines element used to wrap a field. Defaults to 'div'
Choices of 'div', 'tr', 'td', 'ul', 'ol', 'dl' */
'field_el' => 'div',
/* (string) Whether to use the WP uploader or a basic input for image and file fields. Defaults to 'wp'
Choices of 'wp' or 'basic'. Added in v5.2.4 */
'uploader' => 'wp',
/* (boolean) Whether to include a hidden input field to capture non human form submission. Defaults to true. Added in v5.3.4 */
'honeypot' => true,
/* (string) HTML used to render the updated message. Added in v5.5.10 */
'html_updated_message' => '<div id="message" class="updated">%s
</div>',
/* (string) HTML used to render the submit button. Added in v5.5.10 */
'html_submit_button' => false,
/* (string) HTML used to render the submit button loading spinner. Added in v5.5.10 */
'html_submit_spinner' => '<span class="acf-spinner"></span>',
/* (boolean) Whether or not to sanitize all $_POST data with the wp_kses_post() function. Defaults to true. Added in v5.6.5 */
'kses' => true
);
get_header();
acf_form( $settings );
defined('ABSPATH') || exit;
// acf_form_head();
$fields = array(
'presale_certificate', // message
);
acf_register_form(array(
'id' => 'new-user',
'post_id' => 'new_post',
'new_post' => array(
'post_type' => 'post',
'post_status' => 'publish',
'post_title' => $_POST['acf']['_post_title'],
'presale_certificate' => $_POST['acf']['presale_certificate']
),
// 'post_title' => true,
'fields' => $fields,
'post_content' => false,
// 'return' => home_url('bibliographie'),
// 'submit_value' => __("Laisser un message", 'jcd'),
// 'updated_message' => __("Message enregistré", 'jcd'),
));
?>
<!--<input type="file" class="form-control" name="fileToUpload" id="fileToUpload" required>-->
</div>
</div>
</div>
Hello,
I’d like to ask for help because I’m a complete beginner in MYSQL.
I want to sum all Costs where Type is equal to 2 (custom ACF fields):
Type | Cost
0 | 100
2 | 150
1 | 50
2 | 150
In this example the result would be ‘300’. Then I save the result to Options so I can use it often. I was only able to sum the Cost column:
global $wpdb;
$meta_key = 'task_cost';
$cost_s = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$meta_key
)
);
update_field('sa_cost', $cost_s, 'options');
How should I modify the query to get the sum only for selected type (task_type)? Thanks!
When syncing ACF json field definition files between our dev and prod environments, I find the sync process to be really slow at times, and can time out and cause a 50X response.
There appears to be a connection between using a shorter field name in ACF and the length of time that the import process takes, due to the length of some of the content stored in some of our ACF fields, and the number of records we have in the DB.
I’ve found this to be caused by the query in the update_existing_subfields function in the WPML_ACF_Field_Settings class on line 256:
$query = "SELECT * FROM {$wpdb->postmeta} WHERE meta_key LIKE %s";
Suggested Fix:
From what I can see, the update_existing_subfields function is only called by ACF, and only from a single place, in function update_field_settings.
The DB field meta_value included in the output from this query is not used, and in our case it can cause memory usage to rapidly expand and cause PHP to Fatal Error due to a case of Out of Memory.
Therefore, it should be safe to update the query and avoid the meta_value content. On this basis, I’ve found that simply changing line 256 to:
$query = "SELECT post_id, meta_id, meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE %s";
is enough to fix our issues with the Sync Process, and indeed make the process really fast once again.
I use the flexible content field for my pages, basically like a pagebuilder. However, with multiple rows, it can be confusing which is which especially when row types are repeated (image provided). I would love to feature the title on these blocks.
I have found this code, but my only issue is that not all of my subfields are just named “title”. However, they are like “twi_title” or “tb_title”. (The prefixes are named based on what I named the flexible block row.) Is there a way to get the sub field if it just includes “_title” or another way around this?
add_filter('acf/fields/flexible_content/layout_title', function($title) {
$ret = $title;
if ($custom_title = get_sub_field('title')) {
$ret = sprintf('<strong>%s</strong> <em style="font-size: 80%; opacity: 0.5">%s</em>', $custom_title, $title);
}
return $ret;
});
Hi, I have the following code to get a woocommerce product, which is connected with a relationship field. How would I check the post status to show only published Products?
<?php
$related_products = get_field('event_woocommerce_product');
if( $related_products ): ?>
<div class="loop">
<?php foreach( $related_products as $post ):
// Setup this post for WP functions (variable must be named $post).
setup_postdata($post);
?>
<div class="loop-item margin-bottom--m border-bottom--shade-ultra-light margin-bottom--l">
<?php
global $product;
$event_tijd = get_post_meta( $product->get_id(), 'event_tijd', true );
$event_datum = get_post_meta( $product->get_id(), 'event_datum', true );
$date_now = date('Ymd'); // this format is string comparable
?>
<?php if(strtotime($event_datum) >= strtotime($date_now))
{
?>
<h4 class="margin-bottom--xs"> <?php echo $product->get_title(); ?> </h4>
<div class="text--s margin-bottom--xs"><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 20 20">
<path id="Path_391" data-name="Path 391" d="M9.063,4.688a.938.938,0,0,1,1.875,0V9.5l3.332,2.219a.9.9,0,0,1,.227,1.3.86.86,0,0,1-1.266.227l-3.75-2.5a.857.857,0,0,1-.418-.781ZM10,0A10,10,0,1,1,0,10,10,10,0,0,1,10,0ZM1.875,10A8.125,8.125,0,1,0,10,1.875,8.124,8.124,0,0,0,1.875,10Z" />
</svg>
<?php echo $event_tijd;?> </div>
<!-- Prijs en button -->
<?php
echo '<div class="margin-bottom--xs">' . $product->get_price_html() . '</div>';
?>
<?php
echo '<div class="btn--secondary justify-content--center inline-block margin-bottom--xs">';
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="button %s product_type_%s">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product->get_type() ),
esc_html( $product->add_to_cart_text() )
),
$product );
echo '</div>';
?>
<!-- /Prijs en button -->
</div><!-- .loop-item -->
<?php }
else {
echo "";
}?>
<?php endforeach; ?>
</div> <!-- .loop -->
<?php else:
echo 'Nog geen events gepland. Schrijf je in voor onze nieuwsbrief en blijf op de hoogte van nieuwe events!';
?>
<?php
// Reset the global post object so that the rest of the page works correctly.
wp_reset_postdata(); ?>
<?php endif; ?>
I can’t figure out why my ACF gallery is only showing the first image (I have 3 selected in the backend)
`
<?php
// Load value (array of ids).
$image_ids = get_field(‘event_gallery’);
if( $image_ids ) {
// Generate string of ids (“123,456,789″).
$images_string = implode( ‘,’, $image_ids );
// Generate and do shortcode.
// Note: The following string is split to simply prevent our own website from rendering the gallery shortcode.
$shortcode = sprintf( ‘[‘ . ‘gallery ids=”%s”]’, esc_attr($images_string) );
echo do_shortcode( $shortcode );
}
$size = ‘full’; // (thumbnail, medium, large, full or custom size)
if( $images ): ?>
<?php endforeach; ?>
<?php endif; ?>
‘
Hi,
I have a Google Maps field in the backend where I can enter an address or a place name, e.g. Allianz Arena, and it will automatically find the full address for it. This makes it easy for publishers adding an address.
How do I get to display the place name in the frontend?
With the following code from the ACF Google Maps page I can only get the street details, but not the place name, in my example “Allianz Arena”.
<?php
$location = get_field('location');
if( $location ) {
// Loop over segments and construct HTML.
$address = '';
foreach( array('street_number', 'street_name', 'city', 'state', 'post_code', 'country') as $i => $k ) {
if( isset( $location[ $k ] ) ) {
$address .= sprintf( '<span class="segment-%s">%s</span>, ', $k, $location[ $k ] );
}
}
// Trim trailing comma.
$address = trim( $address, ', ' );
// Display HTML.
echo '<p>' . $address . '.</p>';
}
How could I get that place name?
Thanks,
Johannes
I have code to load the last 6 terms and only use terms without children so I get the months and not the years which are both part of the same Taxonomy as terms. I can already load the titles as links, but I am trying to load the attached ACF image field which I am failing to do.
I use $summaryimage = get_field('summary_preview_image');
inside this block.php
file to then use it for wp_get_attachment_image( $summaryimage, $size )
. But it seems that the variable is not loading anything and so my term image is not being loaded. Question is why this is not working inside wp-content/themes/theme/blocks/spotlight/block.php
I am guessing cause I perhaps need to indicate more in the get_field request to grab the image from the specific group which is used to attach a custom filed to the term.. But how?
$args = array( 'hide_empty=0',
'childless' => 1,
'number' => 6,
'orderby' => 'ID',
'order' => 'ASC'
);
$terms = get_terms( 'molecules_of_the_month', $args );
if ( ! empty( $terms ) ) :
$summaryimage = get_field('summary_preview_image');
print_r($summaryimage);
$size = 'full'; // (thumbnail, medium, large, full or custom size)
$count = count( $terms );
$i = 0;
$term_list = '<p class="molecule-of-the-month">';
?>
<div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
<div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
<div class="splide__track">
<ul class="post-grid splide__list">
<?php
if($term_list):
foreach ( $terms as $term ) {
$i++;
$term_list .= '<a href="' . esc_url( get_term_link( $term ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'drughunter' ),
$term->name ) ) . '">' . $term->name . '</a><figure class="post-featured-image">' .
wp_get_attachment_image( $summaryimage, $size )
. '</figure>';
if ( $count != $i ) {
$term_list .= ' · ';
}
else {
$term_list .= '
';
}
}
echo $term_list;
endif; ?>
</ul>
</div>
</div>
</div>
<?php endif;?>
I have a weird use case that goes as follows.
I’m using the google maps field to generate Lat/Lng values. These values are used in two ways. First they’re used in a regular way, they’re returned in relation to their parent post to inject into a front end google maps component to display. That bit is easy.
But I’m also running the hook on acf/save_post
to take the lat/lng values and copying them into a secondary table so they can be transformed into POINT spatial values so I can do geometric calculations on them. In a perfect world I would be able to just have 3 columns, a Primary Key index, the Parent Post ID and the coords encoded into a POINT()
value which I could query with spatial tests which would then give me a list of Post IDs to load.
But this gets much more complicated when it comes to having multiple locations attached to one post because there doesn’t appear to be any way of uniquely checking what fields are already there just how many there are.
My first thought was to add a second column as a sort of “subID” which was populated with the array index of the field as it was returned and then applying a MySQL unique constraint across the Post_ID
column and the subID
column. But that doesn’t cover for if a user deletes a repeater entry because lets say there are 5 entries in the repeater and the user deletes entry 3. Entry 4 would become entry 3, entry 5 would become entry 4 and I’d have to explicitly delete delete the highest subID
of the post ID in a separate query and this is getting very complicated for what should be a simple action.
My burned earth fallback is whenever the acf/save_post
hook is called with the repeater field present, just delete all rows with that post ID and then put them all back in again which will ensure that there is absolute parity between the fields on the wp_postmeta
table and my custom, but there has to be a better way.
Here is my current code that works fine with only one location per post
add_action('acf/save_post', 'geo_write_GIS', 11);
function geo_write_GIS($post_id)
{
if (isset(get_fields($post_id)['location'])) {
global $wpdb;
$location_fields = get_fields($post_id)['location'];
$lat = $location_fields['lat'];
$lng = $location_fields['lng'];
$wkt = "POINT ($lat $lng)";
$table = $wpdb->prefix . '_geo';
$result = $wpdb->query(
$wpdb->prepare(
"INSERT INTO $table (ID, pg)
VALUES (%d, ST_PointFromText(%s, 4326))
ON DUPLICATE KEY UPDATE pg=ST_PointFromText(%s, 4326)",
array(
$post_id,
$wkt,
$wkt
)
)
);
}
}
Hi,
I have a tricky issue to solve.
I have a repeater field (publications) with 2 sub-fields.
title and year.
I need to select from the database all titles from all posts matching a condition (let’s say all titles which include ‘search-term’) but I need the result sorted by the year (the 2nd sub-field).
This is the query I use to fetch the titles.
function get_search_results(): array
{
global $wpdb;
$sql = "SELECT pm.meta_value title, pm.post_id post
FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
WHERE p.post_status = 'publish'
AND pm.meta_key LIKE 'publication_%_title'
AND pm.meta_value LIKE '%search-term%';";
return $wpdb->get_results($sql, ARRAY_A);
}
How can I sort the results by the year?
Thanks a lot!
I am using ACF Pro in combination with a membership plugin WP User Manager, I have added a field group to users but I am trying to trigger an admin notification for a user updating their ACF fields.
I have managed to rip some code from the plugin but this is for a user updating custom fields the plugin supports and not ACF fields.
I have tried to change the $field_keys_to_alert array to the acf field key value and also the acf field name but neither seem to work. Has anyone ever done something similiar?
add_filter( 'account_page_form_fields', function ( $fields ) {
if ( ! wp_verify_nonce( $_POST['account_update_nonce'], 'verify_account_form' ) ) {
return $fields;
}
/**
* Changed this array to the field keys (wpum_ is the prefix)
*/
$field_keys_to_alert = array(
'wpum_custom_field',
);
$changed_data = array();
foreach ( $fields as $group_key => $group_fields ) {
foreach ( $group_fields as $key => $field ) {
if ( ! in_array( $key, $field_keys_to_alert ) ) {
continue;
}
if ( isset( $_POST[ $key ] ) && $_POST[ $key ] !== $field['value'] ) {
$changed_data[ $key ] = array( 'old' => $field['value'], 'new' => $_POST[ $key ] );
}
}
}
if ( empty( $changed_data ) ) {
return $fields;
}
$to = get_option( 'admin_email' );
$subject = 'Alert: User account updated ';
$user = get_user_by( 'id', get_current_user_id() );
$message = esc_html__( 'The following user has updated their account' ) . "<br><br>";
$message .= sprintf( esc_html__( 'Username: %s' ), $user->user_login ) . "<br>";
$message .= sprintf( esc_html__( 'E-mail: %s' ), $user->user_email ) . "<br>";
$message .= sprintf( esc_html__( 'First Name: %s' ), $user->first_name ) . "<br>";
$message .= sprintf( esc_html__( 'Last Name: %s' ), $user->last_name ) . "<br>";
$message .= sprintf( esc_html__( 'Website: %s' ), $user->user_url ) . "<br><br>";
foreach ( $changed_data as $key => $values ) {
$message .= sprintf( esc_html__( '%s:', 'wp-user-manager' ), $key ) . "<br>";
$message .= sprintf( esc_html__( 'From: %s', 'wp-user-manager' ), $values['old'] ) . "<br>";
$message .= sprintf( esc_html__( 'To: %s', 'wp-user-manager' ), $values['new'] ) . "<br><br>";
}
wp_mail( $to, $subject, $message, array( 'Content-Type: text/html; charset=UTF-8' ) );
return $fields;
} );
hi,
My image and alt was working fine before but I just noticed my images and alt is not showing and it’s showing “h”. I didn’t change anything. My backend is showing the image. I’m wondering why is not working. Please see screenshit. This is the code.
<?php
$cat = get_query_var('Category');
$args = array(
'child_of' => $cat,
'orderby' => 'date',
'order' => 'ASC'
);
$categories = get_categories($args);
foreach($categories as $category) {
$image = get_field('cat_thumbnail_image', 'category_'. $category->term_id .'');
echo '<article class="work-wrap">
<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" class="work-img">
<img src="' . $image['url']; ?>" alt="<?php echo $image['alt'] . '">
<h2>'. $category->name . '</h2>
</a>
</article>';
}
?>
I’m currently writing an API on Python.
Goal: Update repeater field. I can change anything else(like text), but working with repeater fields came in a bit of a struggle. For authorization, I’m using the JWT token. ‘cadres’ field doesn’t want to update.
please help 🙁
curHeaders = {
"Authorization": "Bearer %s" % jwt_token,
"Content-Type": "application/json",
"Accept": "application/json",
}
test = ['http://localhost:8888/wp-content/uploads/2021/06/test.jpeg']
postDict = {
'fields': {
'videos': {
'fields': {
'title': 'This is working properly',
'fields': {'cadres': test
}}}}}
lollookatthis = requests.put('http://localhost:8888/wp-json/acf/v3/custom_post/369', headers=curHeaders, json=postDict)
The post/put action returns a JSON with an updated value of ‘title’, but not an updated value of ‘cadres’. It doesn’t return an error, so the post/put request is working as intended, perhaps it’s just the way that ACF works.
I have a form that contains a select menu that is being dynamically populated using custom fields from repeater rows. The dynamic population of the select menu totally works. However, I then want the selection to be tied to a different email address (a custom field in the same repeater) so that the selection determines which email address to send a notification of the form submission.
The repeater name is partners and each row has the following fields: partners_country, for the dynamic population partners_email, for the email address that should be tied to that select option and used to send the notification
The dynamic population works, but the notification filter doesn’t. It always grabs the value/email address of the very last row of the repeater, regardless of which option has been selected in the select menu.
I feel like I’m a few lines of code from this working, but the issue is using $entry
to somehow tie the selection to the email address through an array or something.
If it helps, I was trying to reference this code, where someone is doing this based on WP user meta, rather than grabbing ACF repeater meta:
https://joshuadnelson.com/user-dropdown-list-custom-notification-routing-gravity-forms/
I also found this, but I wsn’t able to adapt it to my needs cause I am not smart enough: https://gist.github.com/tmoitie/9808555
This is the code that does work:
// Populate GF with ACF Repeater
add_filter('gform_pre_render_1', 'dynamic_populate'); // Where 1 is GF ID
function dynamic_populate($form) {
foreach($form['fields'] as &$field){
if(strpos($field['cssClass'], 'region-field') === false)
continue;
global $post;
$id = $post->ID;
global $wpdb;
$rows = $wpdb->get_results($wpdb->prepare(
"
SELECT *
FROM wp_postmeta
WHERE post_id = %d AND meta_key LIKE %s
",
$id,
'partners_%_partners_country'
// repeater-name_%_field-name
));
$choices = array(array('text' => 'Select a Region', 'value' => ' '));
if($rows){
foreach($rows as $row) {
preg_match('_([0-9]+)_', $row->meta_key, $matches);
$meta_key = 'partners_' . $matches[0] . '_partners_country';
$valueText = get_post_meta($post->ID,$meta_key,true);
$value = str_replace(' ', '-', strtolower($valueText));
$choices[] = array('text' => $valueText, 'value' => $value);
}
}
$field->choices = $choices;
}
return $form;
}
This is the code that doesn’t work:
// Route to user address from drop down list, update the '1' to the ID of your form
add_filter('gform_notification_1', 'contact_email_notification', 10, 3);
function contact_email_notification($notification, $form , $entry) {
foreach($form['fields'] as &$field) {
if($field['type'] != 'select' || strpos($field['cssClass'], 'region-field') === false )
continue;
global $post;
$id = $post->ID;
global $wpdb;
$rows = $wpdb->get_results($wpdb->prepare(
"
SELECT *
FROM wp_postmeta
WHERE post_id = %d AND meta_key LIKE %s
",
$id,
'partners_%_partners_email'
// repeater-name_%_field-name
));
// $field_id = (string) $field['id'];
// $post_id = $entry[ $field_id ];
if($rows){
foreach($rows as $row) {
preg_match('_([0-9]+)_', $row->meta_key, $matches);
$meta_key = 'partners_' . $matches[0] . '_partners_email';
$email_to = get_post_meta($post->ID,$meta_key,true);
}
}
}
if (!empty($email_to)) {
$notification['to'] = $email_to;
}
return $notification;
}
Hello everyone, I am facing some issues with a custom query I would like to set up.
It’s a mixing between POST TITLE and ACF. that’s why I cannot use standard WP_QUery.
Below you will find a complex query which is keeping not giving expected results:
All the Posts which have either the given %multi%word%string in the title, or in operations_short_bio or operations_long_bio BUT both of operations field must be retrieved.
$searchStr = preg_replace('/\s+/', '%', $_GET['s']);
$searchStr = "%".$searchStr."%";
SELECT
posts.post_title AS name, posts.ID as ID,
MAX(CASE WHEN (postmeta.meta_key='operations_short_bio') THEN postmeta.meta_value ELSE NULL END) AS short_description,
MAX(CASE WHEN (postmeta.meta_key='operations_long_bio') THEN postmeta.meta_value ELSE NULL END) AS long_description
FROM {$wpdb->base_prefix}posts AS posts
LEFT JOIN {$wpdb->base_prefix}postmeta AS postmeta
ON posts.ID=postmeta.post_id
WHERE
posts.post_type = 'post'
AND
posts.post_status = 'publish'
AND
(
(
postmeta.meta_key
IN('operations_long_bio', 'operations_short_bio')
AND postmeta.meta_value LIKE '$searchStr'
)
OR ( posts.post_title LIKE '$searchStr' )
)
GROUP BY posts.ID,posts.post_title
ORDER BY posts.post_title
the output is a $res array with just one of the acf fields, and the other simply is null 🙁
Hi plugin author, I had implemented ACF PRO latest version in the website,
First of all, sorry for making the duplicate posts
https://support.advancedcustomfields.com/?post_type=topic&p=144579
I have created a flexible content for section and implemented background color and background image for each section,
As per my design , i have created my design almost complete but when the client says to add something above certain section the issue is showing. At first I create a section through flexible content and reorder as per the client needs the background image is showing in two section one with background color and one with background image itself
I had created a dummy page for the issue to show you in my website.
I have also included some pics of the issue.
Here is my code
At page.php file I run a flexible content loop and set the content to desired templates as need.
<?php
//Get subfield values
$section_background = get_sub_field('section_background');
$section_color = get_sub_field('section_background_color');
$section_extra_class = get_sub_field('section_extra_classes');
?>
<?php if (!empty($section_background)): ?>
<?php $unique_id = esc_attr(uniqid('section-'));?>
<style>
#<?php echo $unique_id; ?> {
background-image: url(<?php echo $section_background; ?>);
}
</style>
<?php endif;?>
<section class="section<?php echo sprintf(' %s %s', $section_color, $section_extra_class); ?>" <?php if (isset($unique_id)) {
echo sprintf(' id="%s"', $unique_id); }?>>
<div class="container">
<?php
/**
* Loop through layout types registered in ACF plugin.
* Field group -> "Page Sections" -> "Section" -> "Section Content Types"
*
*/
if (have_rows('section_content_types')):
while (have_rows('section_content_types')): the_row();
//Regular Layout
if (get_row_layout() == 'regular_layout'):
get_template_part('template-parts/page/layout', 'regular');
//Equal Columns Layout
elseif (get_row_layout() == 'equal_column_layout'):
get_template_part('template-parts/page/layout', 'equal-columns');
//Landing Layout
elseif (get_row_layout() == 'landing_layout'):
get_template_part('template-parts/page/layout', 'landing');
//Tabs Layout
elseif (get_row_layout() == 'tabs_layout'):
get_template_part('template-parts/page/layout', 'tabs');
endif;
endwhile;
endif;
?>
</div>
</section>
ACF In posts
When the New Section is added
When Reordering The section
In Inspect Element
here is my issue in Problem.
Hey!
I am hoping someone can help me out.
I suck at Javscript, so I was hoping I could just use the acf_form().
All I want, is a simple button that when clicked, will update certain fields without giving the user the input field. I want it to be hardcoded.
For example, one simple use case. There is a custom post type called “Installs”.
In this custom post type, there is a custom field (ACF true/false field) that is called “Completed”
On the front end list of all installs, I want a button that says “completed” that the user can click and then update [completed] to ‘1’.
I can’t figure out how to do this with the current ACF Form. I can get it to display the true/false field and the button that says “Completed” but I am not sure how to do this without showing the user the true/false field. I want them to just see the ‘submit’ button.
acf_form_head();
acf_form(array(
'post_id' => $id,
'fields' => ['field_605b62244f4dc'],
'post_title' => false,
'post_content' => false,
'return' => '/manufacturing/',
'html_submit_button' => '<input type="submit" class="btn bg-blue small text-uppercase p-1 text-white" value="%s" />',
'submit_value' => __('Save')
));
Hi, I try to create list of child category with images thumbs.
I add new field to taxonomy “image_category” and now I try to add this image to the list:
<?php
$args = array('parent' => 3);
$categories = get_categories( $args );
$term = get_queried_object();
$image_category = get_field('image_category', $term);
foreach($categories as $category) {
echo '<div class="col-md-3 col-sm-12 col-xs-12 lista-kraje text-center pb-3"><img src="' . $image_category . '"><h3><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </h3> ';
echo '<p> <strong>Number post:</strong> '. $category->count . '</p></div>';
}
?>
I see category list, name, number post. Only image dont work.
Image link dont show. I have on consol only “img src=(unknown)”. What am I doing wrong?